/*
 * @Author: hongbin
 * @Date: 2023-10-12 10:12:47
 * @LastEditors: hongbin
 * @LastEditTime: 2023-12-08 10:58:01
 * @Description:
 */
import express from "express";
import * as fs from "fs";
import * as https from "https";
import * as http from "http";
import * as path from "path";
const app = express();
import TextEncoding from "text-encoding";
import { DbNative } from "./MongoNative.js";
import { DbMongoose } from "./Mongoose.js";

app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "content-type,Authorization");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == "options") res.status(200).send();
    else next();
});

const port = process.env.PORT || 3002;

const httpServer = http.createServer(app);

if (process.env.NODE_ENV === "production") {
    httpServer.listen(port, () => {
        console.log("> pro mode on http🎉" + port);
    });
} else {
    httpServer.listen(port, () => {
        console.log("> dev mode on http🎉" + port);
    });
}

app.get("*", (req, res, next) => {
    console.log("get:", req.url);
    console.log(decodeURIComponent(req.url));
    res.json({ msg: "hello" });
});

app.post("*", (req, res, next) => {
    let payload = "";
    req.on("data", chunk => (payload += chunk));
    req.on("end", () => {
        try {
            req.payload = JSON.parse(payload);
        } catch (error) {
            res.status(666).json({ msg: "body格式不对啊" });
        } finally {
            next();
        }
    });
});

import crypto from "crypto";
import jsonwebtoken from "jsonwebtoken";

const secret = "9AsW&AKW71!ws%o^";

const token =
    ".eyJ1c2VySW5mbyI6IntcbiAgICBcInVzZXJOYW1lXCI6XCLlvKDkuIlcIixcbiAgICBcImxvZ2luTmFtZVwiOlwiemhhbnNoYW5cIixcbiAgICBcInBob25lXCI6XCIxNDc4MTgzNTMwMFwiLFxuICAgIFwiY29kZVwiOlwiMDFcIlxufSIsImlzcyI6InRpcHNQZXJhIiwiZXhwIjoxNzAyMDAyMjk2fQ.EnmYLDsY2tYezxv3Dey_27Tacby4ycp4AAtlUnQAVrQ";

console.log("-------------");
// const payload = jsonwebtoken.verify(token, secret, { algorithms: ["HS256"] });
// console.log(payload);
console.log(JSON.parse(Buffer.from(token.split(".")[1], "base64").toString()));
// function createDigest(encodedData, format) {
//     return crypto
//         .createHmac("sha256", secret)
//         .update(encodedData)
//         .digest(format);
// }

// function encode(sourceData) {
//     const json = JSON.stringify(sourceData);
//     const encodedData = Buffer.from(json).toString("base64");
//     return `${encodedData}!${createDigest(encodedData, "base64")}`;
// }

// function decode(value) {
//     let [encodedData, sourceDigest] = value.split("!");
//     if (!encodedData || !sourceDigest) throw new Error("invalid value(s)");
//     const json = Buffer.from(encodedData, "base64").toString("utf8");
//     const decodedData = JSON.parse(json);
//     const checkDigest = createDigest(encodedData);
//     const digestsEqual = crypto.timingSafeEqual(
//         Buffer.from(sourceDigest, "base64"),
//         checkDigest
//     );
//     if (!digestsEqual) throw new Error("invalid value(s)");
//     return decodedData;
// }

// const data = { name: "brian" };
// const encoded = encode(data);
// const decoded = decode(encoded);

// console.log("original data", data);
// console.log("encoded as", encoded);
// console.log("encoded size", Buffer.byteLength(encoded, "utf8"));
// console.log("decoded as", decoded);

/**
 * @description 使用 mongodb 连接
 * @link https://github.com/mongodb/node-mongodb-native
 */
// const Db = new DbNative();

// console.log(await Db.listCollections());

/**
 * @description 使用 mongoose 连接
 * @link https://github.com/Automattic/mongoose
 */
// const Db = new DbMongoose(app);

// console.log(await Db.RoleManager.admin);

// Db.RoleManager.findAll()
//   .then(res => {
//     console.log("res", res);
//   })
//   .catch(err => {
//     console.log("err", err);
//   });

// Db.RoleManager.insert({ desc: "游客", name: "TOURIST" })
//   .then(res => {
//     console.log("res", res);
//   })
//   .catch(err => {
//     console.log("err", err);
//   });
// Db.ProjectManager.findAll()
//   .then(res => {
//     console.log("res", res);
//   })
//   .catch(err => {
//     console.log("err", err);
//   });

// console.log(await Db.listCollections());
